<template>
  <div class="container">
    <div id="aside">
      <img style="float: left;" id="logo" src="@/assets/logo1.png" alt="logo" />

      <el-button style="margin-top: 50px;" circle id="menu" type="primary" @click="this.buyVisible = true">
        <el-icon>
          <ShoppingCart />
        </el-icon>
        <span class="text">套餐</span>
      </el-button>
      <br>

      <el-button circle id="menu" type="primary" @click="this.orderVisible = true">
        <el-icon>
          <Tickets />
        </el-icon>
        <span class="text">订单</span>
      </el-button>
      <br>

      <el-button style="margin-top: 50vh;" circle id="menu" type="primary" @click="this.userInfoVisible = true">
        <el-icon style="font-size: 30px;">
          <User />
        </el-icon>
        <!-- <span class="text">个人中心</span> -->
      </el-button>

    </div>
    <div id="history">
      <div style="position: fixed;width: 15%;background-color: #fff;border-top-left-radius: 20px;">
        <el-button
          style="background-color: #6964EF;border-radius: 20px;width: 70%;height: 44px;margin-top: 30px;margin-bottom: 30px;"
          type="primary" @click="addChat">
          <el-icon style="font-size: 18px">
            <Plus />
          </el-icon><span style="font-size: 18px;">新建对话</span> </el-button>
      </div>

      <!-- 遍历hittoryList显示 -->
      <div style="margin-top: 150px;">
        <div v-for="(item, index) in historyList" :key="index" style="margin-top: 18px;">
          <div id="historyItem" :class="{ 'selected-history': item.id === currentChat.id }" @click="changeChat(item)"
            type="primary">
            <span style="width: 80%;display: inline-block;overflow: hidden;padding-left: 10px;">{{ item.title }}</span>
            <el-button v-show="item.id == currentChat.id && item.allMessages.length > 0"
              style="float: right;height: 40px;border: none;background: none;" type="primary" @click="deleteChat(item)">
              <el-icon style="color: red;">
                <Delete />
              </el-icon></el-button>
          </div>
        </div>
      </div>
    </div>
    <div id="main">
      <!-- <el-input style="width: 60%;margin-left: 20%;margin-top: 30px;" type="textarea" :rows="20" v-model="answer">
      </el-input> -->

      <!-- 循环遍历allMessages,并显示 -->
      <p style="margin-bottom: 33px;"></p>
      <div class="chat-wrapper" style="width: 80%;margin-left: 10%;height: 80vh; overflow: scroll;">
        <div style="display: flex; margin-bottom: 20px;" v-for="(item, index) in allMessages" :key="index">
          <div style=" margin-left: auto;" v-if="item.role === 'user'">
            <span id="userMsg">
              {{ item.content }}
            </span>
          </div>

          <div style=" margin-right: auto;" v-else>
            <img style="width: 30px; height: 30px;float: left;" src="@/assets/logo1.png" alt="logo" />
            <span id="aiMsg">
              {{ item.content }}
            </span>
          </div>
        </div>
      </div>

      <div class="input-wrapper">
        <el-input class="input-bottom" placeholder="请输入你的问题" v-model="message" @keydown.enter="chat">
          <template #suffix>
            <el-button @click="chat" :disabled="this.message.length == 0"
              :style="{ height: '40px', width: '40px', backgroundColor: getButtonColor(), fontSize: '18px', color: 'white' }"
              icon="Promotion" circle></el-button>
          </template>
        </el-input>
        <!-- <br> -->
        <!-- <el-button type="primary" @click="saveHistory">saveHistory</el-button> -->
        <!-- <el-button type="primary" @click="logHistory">logHistory</el-button> -->

      </div>



    </div>

    <el-dialog style="" v-if="buyVisible" append-to-body v-model="buyVisible" title="套餐" width="70%">

      <Buy />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="buyVisible = false">
            关闭
          </el-button>
        </div>
      </template>

    </el-dialog>

    <el-dialog v-if="orderVisible" append-to-body v-model="orderVisible" title="订单" width="70%"
      style="overflow: scroll;">

      <Orders />

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="orderVisible = false">
            关闭
          </el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-if="userInfoVisible" append-to-body v-model="userInfoVisible" title="用户信息" width="70%"
      style="overflow: scroll;">

      <UserInfo />
      <template #footer>
        <div class="dialog-footer">
          <!-- <el-button @click="buyVisible = false"></el-button> -->
          <el-button type="primary" @click="userInfoVisible = false">
            关闭
          </el-button>
        </div>
      </template>
    </el-dialog>



  </div>
</template>

<script>
import Buy from '@/views/GoodsView'
import Orders from '@/views/OrderView'
import UserInfo from '@/views/UserInfo'
import { EventSourcePolyfill } from 'event-source-polyfill';
import { saveHistory, listHistory, deleteHistory } from '@/api/chat'
import { getUserInfo } from '@/api/user'
export default {
  components: {
    Buy,
    Orders,
    UserInfo

  },


  data() {
    return {
      historyList: [],
      currentChat: {},
      allMessages: [],
      // allMessages: [
      //   {
      //     role: 'user',
      //     content: '你好'
      //   },
      //   {
      //     role: 'ai',
      //     content: '你好,有什么问题吗'
      //   }, {
      //     role: 'user',
      //     content: '你好'
      //   },
      //   {
      //     role: 'ai',
      //     content: '你好,有什么问题吗?有什么问题吗??'
      //   }, {
      //     role: 'user',
      //     content: '你好'
      //   },
      //   {
      //     role: 'ai',
      //     content: '你好!!!!'
      //   },
      // ],
      message: '',
      answer: '',
      buyVisible: false,
      orderVisible: false,
      userInfoVisible: false,
    }
  },
  methods: {

    logHistory() {
      console.log(this.historyList);
    },

    changeChat(item) {
      console.log(item);
      this.currentChat = item
      this.allMessages = item.allMessages

    },

    addChat() {
      //如果已有空对话,不创建
      if (this.historyList.length > 0 && this.historyList[0].allMessages.length == 0) {
        if (this.currentChat == this.historyList[0]) {
          this.$message.warning('已是最新对话')
        }
        this.currentChat = this.historyList[0]
        this.allMessages = this.currentChat.allMessages
        return;
      }

      //添加到historyList的开头
      this.historyList.unshift({
        title: '新对话',
        allMessages: []
      })
      this.changeChat(this.historyList[0])

    },

    deleteChat(item) {
      deleteHistory(item.id).then(res => {
        // console.log(res);
        if (res.code == 1) {
          this.$message.success('删除成功')
          this.loadHistoryChat();
          this.currentChat = this.historyList[0]
        } else {
          this.$message.error(res.msg)
        }

      })

    },

    getButtonColor() {
      // 根据message的值动态计算颜色
      if (this.message.length == 0) {
        return '#D6D5DE';
      } else {
        return '#5C56E3';
      }
    },
    chat() {
      if (this.message.length == 0) {
        return;
      }
      //判断token余额
      getUserInfo().then(res => {
        // console.log(res);
        if (res.data.token <= 0) {
          this.$message.warning('token余额不足,请先充值');
          return;
        }
        const url = `http://127.0.0.1:1145/ai/chat?message=${this.message}`;
        // const eventSource = new EventSource(url,{
        const eventSource = new EventSourcePolyfill(url, {
          headers: {
            token: localStorage.getItem('token')
          }
        });
        this.allMessages.push({
          role: 'user',
          content: this.message
        });
        this.answer = ''
        this.message = '';

        this.allMessages.push({
          role: 'ai',
          content: this.answer
        });
        eventSource.onmessage = (event) => {
          if (event.data !== '[DONE]') {
            this.answer += event.data.replace(/\\x0A/g, '\n');
            const container = document.querySelector('.chat-wrapper');
            container.scrollTop = container.scrollHeight;
          } else {

            eventSource.close();
            this.saveHistory();
            // this.loadHistoryChat();
          }
          // console.log(this.answer);
          this.allMessages[this.allMessages.length - 1].content = this.answer;
        };
        eventSource.onerror = (error) => {
          console.error("EventSource failed:", error);
          this.messages.push("Error receiving stream data");
          eventSource.close();
        };
      })

    },

    saveHistory() {
      //封装json   historyId 和 allMessages
      var history = {
        historyId: this.currentChat.id,
        allMessages: this.allMessages
      }

      saveHistory(history).then(res => {
        console.log(res);

        if (res.code == 1) {
          this.$message.success("保存成功")
        } else {
          this.$message.error("保存失败")
        }

        listHistory().then(res1 => {
          console.log(res1);
          this.historyList = res1.data
        })

      })

    },
    loadHistoryChat() {
      listHistory().then(res => {
        console.log(res);
        this.historyList = res.data
      })
    }
  },

  mounted() {
    this.loadHistoryChat()
  }
}
</script>

<style scoped>
.container {
  display: flex;
  height: 100vh;
}

#aside {
  width: 4.3%;
  height: 100vh;
  float: left;
}

#history {
  width: 15%;
  height: 98vh;
  margin-top: 1vh;
  background-color: #fff;
  float: left;
  border-top-left-radius: 20px;
  border-bottom-left-radius: 20px;
  overflow-y: scroll;
  overflow-x: hidden;
}

#historyItem {
  width: 80%;
  margin-left: 10%;
  background: none;
  color: black;
  border: none;
  border-radius: 10px;
  overflow: hidden;
  height: 40px;
  line-height: 40px;
  text-align: left;
}

#historyItem:hover {
  background-color: #F3F2FF;
  color: #6965EE;
  cursor: pointer;
}

.selected-history {
  background-color: #F3F2FF !important;
  color: #615CED !important;
}

#main {
  width: 80%;
  height: 98vh;
  margin-top: 1vh;
  background-color: #F7F8FC;
  float: left;
  border-top-right-radius: 20px;
  border-bottom-right-radius: 20px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

#logo {
  width: 90%;
  height: 55px;
  margin-top: 30px;
}

#menu {
  width: 60px;
  height: 60px;
  background-color: #A48DF4;
  border: none;
  margin-bottom: 30px;
}

#buy:hover {
  border: 1px solid #A48DF4;
}

.input-wrapper {
  margin-top: auto;
  /* width: 60%; */
  /* margin-left: 20%; */
  height: 60px;
  /* border-radius: 20px; */
  position: relative;
  bottom: 30px;
}

.input-bottom {
  margin-top: auto;
  width: 60%;
  /* margin-left: 20%; */
  height: 58px;
  border-radius: 20px;
  position: relative;
  /* bottom: 50px; */
}


#userMsg {
  text-align: right;
  display: block;
  height: 40px;
  line-height: 40px;
  background-color: #E0DFFF;
  border-radius: 10px;
  padding: 0 10px;
}

#aiMsg {
  text-align: left;
  display: inline-block;
  line-height: 40px;
  background-color: #fff;
  border-radius: 10px;
  padding: 0 10px;
}



/deep/ .el-input {
  --el-input-border-radius: 30px;
  --el-input-border: none;
  --el-input-border-color: none;
  --el-input-hover-border-color: green;
  --el-input-focus-border-color: purple;
}

/deep/ .el-input__inner {
  font-size: 18px;
  margin-left: 30px;
}

::-webkit-scrollbar {
  width: 7px;
  border-radius: 10px;
}

/* Track */
::-webkit-scrollbar-track {
  background: #fff;
}

/* Handle */
::-webkit-scrollbar-thumb {
  background: #E0E2EB;
  border-radius: 10px;
}

/* Handle on hover */
::-webkit-scrollbar-thumb:hover {
  background: #C6C4FF;
}
</style>
